<template>
    <div class="container">
      <div class="sidebar">
        <el-tree 
        :data="raindata" 
        :props="dPs" 
        @node-click="handleNodeClick" 
        :current-node-key='currentKey' 
        default-expand-all 
        :highlight-current="highlightBd"
        node-key="id"
        ref="treeRef"
        ></el-tree>
      </div>
      <div class="content">
        <!-- activeName -->
        <el-tabs v-model="activeName"  @tab-click="handleClick">
          <!-- <el-button @click="getList"> get</el-button> -->
        
          <el-tab-pane label="雨量数据图" name="first">
            <div class="chart-container">
              <chart v-loading="loading" height="100%" width="100%" :chatData="chatData" :chartRiqi="chartRiqi" />
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="降雨速率图" name="second"></el-tab-pane> -->
          <!-- <el-tab-pane label="刨面内侧点缩略图" name="third"></el-tab-pane> -->
        </el-tabs>
      </div>
      
      
    </div>
  </template>
  
  <script>
  import chart from '../../components/charts/Mix-rain.vue'
  import { getDeviceRainData, listDevice } from "@/api/screen/device";
  
  export default {
    name: 'graph',
    components: { chart },
    data() {
      return {
        currentKey: 0 ,
        activeName: 'first',
        chatData: [
          // 150, 230, 224, 218, 135, 147, 262
          // 10, 10, 10, 1, 1, 1, 1

        ],
        chartRiqi: [
          // '2023-11-11', '2023-11-12', '2023-11-13', '2023-11-14', '2023-11-15', '2023-11-16', '2023-11-17'
        ],
        deviceRainDataList: [],
        highlightBd: true,
        raindata: [],
        activeName: 'first',
        deviceList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        elTreeData: [],
        loading: true,
        // groupedDevices: {}
      }
    },
    computed: {
      dPs() {
        return {
          children: 'children',
          label: 'label'
        };
      }
    },
    mounted() {
      this.getList()
      // this.getListNew()
      // this.checkedKeys = 124

    },
    // created() {
    //  this.loading = true;
    // //  this.fetchDeviceIdAndList();
    // },
    methods: {
      handleClick (tab, event) {
        console.log(tab, event)
      },

      

       /** 查询设备列表 */
      getList() {
        this.loading = true;
        listDevice({monitorDeviceName:'雨量',  pageSize:20}).then(response => {
          console.log('deviceList',response.rows) 
          // this.deviceList = myList
          this.deviceList = response.rows
          this.groupByDeviceId()

            // 选择并处理第一个树节点
          if (this.raindata.length > 0 && this.raindata[0].children && this.raindata[0].children.length > 0) {
            const firstNodeId = this.raindata[0].children[0].id;
            console.log('firstNodeId',firstNodeId)
            this.handleNodeClick({id: firstNodeId});

             // this.convertToElTree()
        console.log('this.deviceList', this.deviceList)
            console.log('123',firstNodeId,this.currentKeys)
          }
            this.groupByDeviceId()

            // this.convertToElTree()
            console.log('this.deviceList', this.deviceList)
            // monitordevicecode 所属监测点
            // monitordevicename 设备类型
            // deviceid  设备id
            this.total = response.total;
            this.loading = false;
          }).catch(error => {
    console.error("Error fetching device list:", error);
    this.loading = false;
        }
      );
      },
      
      /** 查询降雨量设备数据详情 */
      getDeviceRainData(e) {
        this.loading = true;
        getDeviceRainData({deviceId:e, isAsc:'desc', orderByColumn:'createTime'}).then(response => {
          console.log('deviceRainDataList',response.rows) 
          this.loading = false
          // let resList = response.rows
          this.deviceRainDataList = response.rows
          // this.deviceRainDataList = resList.reverse()
          this.chartRiqi = this.deviceRainDataList.map(item=> {return item.createTime})
          this.chatData = this.deviceRainDataList.map(item=> {return item.tag})
          console.log('this.chatData', this.chatData, this.chartRiqi)
          }
        );
      },
      handleNodeClick(raindata) {
        console.log('raindata',raindata, raindata.id);
        if( raindata.id == null) {
          console.log('null')
        } else {
          this.getDeviceRainData(raindata.deviceId)
          this.currentKey = raindata.deviceId
          this.$nextTick(() => {
            this.$refs['treeRef'].setCurrentKey(this.currentKey)
          })
        }
      },
      // 函数根据 deviceId 对设备进行分组
      groupByDeviceId(devices = this.deviceList) {
        return devices.reduce((groups, device) => {
          const { deviceId } = device;
          if (!groups[deviceId]) {
            groups[deviceId] = [];
          }
          groups[deviceId].push({
            label: device.deviceName,
            ...device
          });
          console.log('groups', groups)
          this.groupedDevices = groups


          // 将分组转换为 el-tree 的数据格式（每个分组一个树）
          this.raindata = Object.keys(this.groupedDevices).map(deviceId => {
            return {
              label: `位置编号 ${deviceId}`,
              children: this.groupedDevices[deviceId],
              
              // children: this.groupedDevices[{ id: device.deviceId, label: device.deviceName  }]
            };
          });
          return groups;
        }, {});
      },

      // 使用groupByDeviceId函数进行分组
      // const groupedDevices = groupByDeviceId(deviceList);

      // 将分组转换为 el-tree 的数据格式（每个分组一个树）
      // const treesData = Object.keys(groupedDevices).map(deviceId => {
      //   return {
      //     label: `设备编号 ${deviceId}`,
      //     children: groupedDevices[deviceId]
      //   };
      // });

      convertToElTree(e = this.deviceList) {
          const tempMap = new Map(); // 临时 Map 用于合并相同项
          // 遍历设备列表
          e.forEach(device => {
            if (tempMap.has(device.monitorDeviceCode) ) {
               // 如果存在相同设备名称的项，则合并
               const existingDevice = tempMap.get(device.monitorDeviceCode);
              //  const existingMonitordevicename = tempMap.get(device.monitordevicename);
               existingDevice.children.push({ id: device.deviceId, label: device.deviceName });
            } else {
               // 如果不存在相同设备名称的项，则创建新节点
               tempMap.set(device.monitorDeviceCode, {
                label: device.monitorDeviceCode,
                
                children: [{ id: device.deviceId, label: device.deviceName  }]
              });
              // 如果不存在相同设备名称的项，则创建新节点
              
            }
          });
          
          // 将 Map 转换为数组，存储到 elTreeData 中
          this.elTreeData = Array.from(tempMap.values());

          this.raindata = this.elTreeData
          console.log('this.elTreeData', this.elTreeData)
        }
    }
  }
  </script>
  
  <style  lang="scss">

  /* .el-tree-node:focus > .el-tree-node__content {
    background-color: #66b1ff87 !important;
  }
  .el-tree-node__content:hover {    background-color: #66b1ff87;
  }
  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #66b1ff87;
  } */

.container .sidebar {
  // 修改高亮背景色和color
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    // background-color: #fcf5f3;
    color: #409eff;
  }
  // .el-tree-node:focus > .el-tree-node__content {
  //   color:  #409eff;
  //   /* transition: background 1s; */
  // }
}
  
  
  
  /* .container .sidebar {
    .el-tree-node:focus > .el-tree-node__content {
      background-color: rgba(135, 206, 235, 0.3);
      color: #409eff; //节点的字体颜色
      font-weight: bold;
    }
  } */


.container {
    display: flex;
  }

    
  .sidebar {
    width: 200px; /* Adjust the width as per your layout */
    height: 100vh;
  }
  
  .content {
    flex: 1;
    height: 100vh;
  }
  

  .chart-container{
  position: relative;
  width: 100%;
  height: 80vh;
}



  </style>